# -*-coding:utf-8-*-
import datetime

from django.conf import settings
from celery_tasks.sms import tasks as sms_tasks
from orders.models import OrderInfo
from celery_tasks.email.tasks import send_verify_email
from utils.exceptions import logger


def loan_maturity():
    """
    借阅即将到期.发送提醒归还的短信和邮件
    :return:
    """
    try:
        now = datetime.datetime.now()
        orders = OrderInfo.objects.all()
        for order in orders:
            delta = now - orders
            if delta.days < settings.REMIND_TIME:
                # 发短信
                mobile = order.user.mobile
                content = "您的借阅还有{}天到期,请及时归还...".format(delta.days)
                sms_tasks.send_sms_code.delay(mobile, content, '5')
                # 发邮件
                email = [order.user.email]
                html_message = '''<p>尊敬的读者您好！</p>
                                   <p>感谢您使用智慧图书馆。</p>
                                   <p>您借阅的图书还有{}天即将到期,请您及时归还...</p>'''.format(delta.days)
                send_verify_email.delay(email, html_message)

            elif delta.days < 0:
                # 发短信
                mobile = order.user.mobile
                content = "您的借阅已超期{}天,请及时归还...".format(-int(delta.days))
                sms_tasks.send_sms_code.delay(mobile, content, '5')
                # 发邮件
                email = [order.user.email]
                html_message = '''<p>尊敬的读者您好！</p>
                                  <p>感谢您使用智慧图书馆。</p>
                                  <p>您的借阅已超期{}天,请及时归还....</p>'''.format(-int(delta.days))
                send_verify_email.delay(email, html_message)
    except Exception as e:
        logger.error(e)


